﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ePhoneBook.Models;
using System.IO;
using ePhoneBook.Report;
using ePhoneBook.ReportingWebService;
using System.Net;
using System.Text.RegularExpressions;

namespace ePhoneBook.Controllers
{
    public class ReportController : Controller
    {
        public ActionResult LoadReport()
        {
            string orderBy = string.Empty;
            if (Request.Params.Count > 0 && !string.IsNullOrEmpty((orderBy = Request.Params.Get("OrderBy"))))
            {
                string whereClause = "";
                string pageIndex = "";
                string pageSize = "";
                LoadReport(whereClause, pageIndex, pageSize, orderBy);
            }
            return View("Transaction");
        }

        public ActionResult Export()
        {
            return View("Transaction");
        }

        [HttpPost]
        public ActionResult LoadReport(ReportTransactionModel model)
        {
            string whereClause = model.WhereClause;
            string pageIndex = model.PageIndex;
            string pageSize = model.PageSize;
            LoadReport(whereClause, pageIndex, pageSize, string.Empty);
            return View("Transaction");
        }

        private string SortField(string orderBy)
        {
            if (string.IsNullOrEmpty(orderBy))
            {
                return orderBy;
            }
            return orderBy.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
        }

        private SortDirection GetSortDirection(string orderBy)
        {
            if (string.IsNullOrEmpty(orderBy))
            {
                return SortDirection.None;
            }
            if (orderBy.LastIndexOf("desc", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return SortDirection.DESC;
            }
            return SortDirection.ASC;
        }

        private void LoadReport(string whereClause, string pageIndex, string pageSize, string orderBy)
        {
            string sortDirection = SortDirection.ASC.ToString();
            if (GetSortDirection(orderBy) == SortDirection.ASC)
            {
                sortDirection = SortDirection.DESC.ToString();
            }
            IList<ParameterValue> parameters = new List<ParameterValue>();
            parameters.Add(new ParameterValue { Name = "WhereClause", Value = whereClause == null ? "" : whereClause });
            parameters.Add(new ParameterValue { Name = "GroupBy", Value = "" });
            parameters.Add(new ParameterValue { Name = "LanguageKey", Value = "en-US" });
            parameters.Add(new ParameterValue { Name = "HavingClause", Value = "" });
            parameters.Add(new ParameterValue { Name = "PageIndex", Value = pageIndex == null ? "0" : pageIndex });
            parameters.Add(new ParameterValue { Name = "PageSize", Value = pageSize == null ? "30" : pageSize });
            parameters.Add(new ParameterValue { Name = "TLZone", Value = "-5" });
            parameters.Add(new ParameterValue { Name = "TSZone", Value = "HCM" });

            parameters.Add(new ParameterValue { Name = "OrderBy", Value = orderBy == null ? "" : orderBy });
            parameters.Add(new ParameterValue { Name = "SortField", Value = SortField(orderBy) });
            parameters.Add(new ParameterValue { Name = "SortDirection", Value = sortDirection });

            byte[] output;
            string extension, mimeType, encoding;
            string reportName = "/YepexMexico/Transactions";
            Warning[] warnings;
            string[] streamIds;

            NetworkCredential au = new NetworkCredential("reports", "r3p0rt!2", "yp-server");
            ReportExporter.Export(
                "ReportExecutionServiceSoap" /* name of the WCF endpoint from Web.config */,
                au,
                reportName,
                parameters.ToArray(),
                ExportFormat.HTML4,
                out output,
                out extension,
                out mimeType,
                out encoding,
                out warnings,
                out streamIds
            );

            //-------------------------------------------------------------
            // Set HTTP Response Header to show download dialog popup
            //-------------------------------------------------------------
            //Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
            string source = System.Text.Encoding.UTF8.GetString(output);
            ViewData["Report"] = ReplaceUrlSort(GetSortDirection(orderBy), Request.Url.GetLeftPart(UriPartial.Path), source);

            //return new FileContentResult(output, mimeType);
        }

        private string ReplaceUrlSort(SortDirection sortDirection, string urlReplace, string source)
        {
            MatchCollection matchCollection = Regex.Matches(source, @"<a[^>]*>(.*?)</a>");
            matchCollection = Regex.Matches(source, "href=\"(.*?)\"");
            if (matchCollection == null || matchCollection.Count <= 0)
            {
                return source;
            }
            foreach (Match item in matchCollection)
            {
                /*href="http://yp-server.pyco.vn/ReportServer?%2FYepexMexico%2FTransactions&WhereClause=&GroupBy=&LanguageKey=en-US&PageIndex=0&PageSize=30&HavingClause=&SortDirection=ASC&SortField=Mobile&OrderBy=Mobile%20DESC&TotalRecord=828&TLZone=-5&TSZone=HCM&rs%3AParameterLanguage=&rc%3AParameters=Collapsed&rc%3AToolbar=False"
                
                 Replace to Request.Url.AbsoluteUri?OrderBy=Mobile%20DESC
                 */
                string value = item.Value;
                string orderBy = null;
                MatchCollection matchCollectionOrderBy = Regex.Matches(value, @"OrderBy=\w*%\w*");
                if (matchCollectionOrderBy == null || matchCollectionOrderBy.Count == 0)
                {
                    matchCollectionOrderBy = Regex.Matches(value, @"OrderBy=\w*");
                }
                if (matchCollectionOrderBy == null || matchCollectionOrderBy.Count == 0)
                {
                    continue;
                }
                orderBy = matchCollectionOrderBy[0].Value;
                if (!string.IsNullOrEmpty(orderBy))
                {
                    orderBy = orderBy.Trim();
                    if (sortDirection != SortDirection.None)
                    {
                        int index = orderBy.LastIndexOf("desc", StringComparison.OrdinalIgnoreCase);
                        if (index != -1)
                        {
                            orderBy = orderBy.Substring(0, index) + (sortDirection == SortDirection.DESC ? " ASC" : " DESC");
                        }
                        else
                        {
                            index = orderBy.LastIndexOf("asc", StringComparison.OrdinalIgnoreCase);
                            if (index != -1)
                            {
                                orderBy = orderBy.Substring(0, index) + (sortDirection == SortDirection.DESC ? " ASC" : " DESC");
                            }
                            else
                            {
                                orderBy += (sortDirection == SortDirection.DESC ? " ASC" : " DESC");
                            }
                        }
                    }
                    orderBy = "?" + orderBy;
                    source = source.Replace(value, string.Format("href=\"{0}{1}\"", urlReplace, orderBy));
                }
            }
            return source;
        }

        //public FileResult ViewChart(SeriesChartType chartType)
        //{
        //    IList<ResultModel> peoples = _resultService.GetResults();
        //    Chart chart = new Chart();
        //    chart.Width = 700;
        //    chart.Height = 300;
        //    chart.BackColor = Color.FromArgb(211, 223, 240);
        //    chart.BorderlineDashStyle = ChartDashStyle.Solid;
        //    chart.BackSecondaryColor = Color.White;
        //    chart.BackGradientStyle = GradientStyle.TopBottom;
        //    chart.BorderlineWidth = 1;
        //    chart.Palette = ChartColorPalette.BrightPastel;
        //    chart.BorderlineColor = Color.FromArgb(26, 59, 105);
        //    chart.RenderType = RenderType.BinaryStreaming;
        //    chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
        //    chart.AntiAliasing = AntiAliasingStyles.All;
        //    chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
        //    chart.Titles.Add(CreateTitle());
        //    chart.Legends.Add(CreateLegend());
        //    chart.Series.Add(CreateSeries(peoples, chartType));
        //    chart.ChartAreas.Add(CreateChartArea());

        //    MemoryStream ms = new MemoryStream();
        //    chart.SaveImage(ms);
        //    return File(ms.GetBuffer(), @"image/png");
        //}
    }
}
